package com.zg.autoform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.autoform.dto.ImportFieldConfig;
import com.zg.autoform.service.ImportFieldConfigService;
import com.zg.common.core.dao.autoform.DiyImportFieldConfig;
import com.zg.common.core.dao.autoform.DiyImportFieldConfigDao;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 导入字段配置服务实现
 * @author zg
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ImportFieldConfigServiceImpl implements ImportFieldConfigService {

    private final DiyImportFieldConfigDao fieldConfigDao;

    @Override
    public List<DiyImportFieldConfig> getFieldConfigsByTemplateId(Long templateId) {
        return fieldConfigDao.list(
            new LambdaQueryWrapper<DiyImportFieldConfig>()
                .eq(DiyImportFieldConfig::getTemplateId, templateId)
                .orderByAsc(DiyImportFieldConfig::getSortOrder)
        );
    }

    @Override
    public List<ImportFieldConfig> getFieldConfigDtosByTemplateId(Long templateId) {
        List<DiyImportFieldConfig> entities = getFieldConfigsByTemplateId(templateId);
        return entities.stream()
            .map(this::convertToDto)
            .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFieldConfigs(Long templateId, List<ImportFieldConfig> fieldConfigs) {
        // 1. 删除原有配置
        deleteFieldConfigsByTemplateId(templateId);

        // 2. 保存新配置
        if (fieldConfigs != null && !fieldConfigs.isEmpty()) {
            List<DiyImportFieldConfig> entities = new ArrayList<>();
            
            for (int i = 0; i < fieldConfigs.size(); i++) {
                ImportFieldConfig dto = fieldConfigs.get(i);
                DiyImportFieldConfig entity = convertToEntity(dto);
                entity.setTemplateId(templateId);
                
                // 如果没有设置排序，使用索引
                if (entity.getSortOrder() == null) {
                    entity.setSortOrder(i + 1);
                }
                
                entities.add(entity);
            }
            
            fieldConfigDao.saveBatch(entities);
            log.info("保存字段配置成功，模板ID: {}, 字段数量: {}", templateId, entities.size());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFieldConfigsByTemplateId(Long templateId) {
        fieldConfigDao.remove(
            new LambdaQueryWrapper<DiyImportFieldConfig>()
                .eq(DiyImportFieldConfig::getTemplateId, templateId)
        );
        log.info("删除字段配置成功，模板ID: {}", templateId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void copyFieldConfigs(Long sourceTemplateId, Long targetTemplateId) {
        List<DiyImportFieldConfig> sourceConfigs = getFieldConfigsByTemplateId(sourceTemplateId);
        
        if (!sourceConfigs.isEmpty()) {
            List<DiyImportFieldConfig> targetConfigs = sourceConfigs.stream()
                .map(source -> {
                    DiyImportFieldConfig target = new DiyImportFieldConfig();
                    BeanUtil.copyProperties(source, target, "id", "templateId", "createTime", "createBy");
                    target.setTemplateId(targetTemplateId);
                    return target;
                })
                .collect(Collectors.toList());
            
            fieldConfigDao.saveBatch(targetConfigs);
            log.info("复制字段配置成功，源模板ID: {}, 目标模板ID: {}, 字段数量: {}", 
                sourceTemplateId, targetTemplateId, targetConfigs.size());
        }
    }

    /**
     * 实体转DTO
     */
    private ImportFieldConfig convertToDto(DiyImportFieldConfig entity) {
        ImportFieldConfig dto = new ImportFieldConfig();
        BeanUtil.copyProperties(entity, dto);
        dto.setSort(entity.getSortOrder()); // 字段名映射
        return dto;
    }

    /**
     * DTO转实体
     */
    private DiyImportFieldConfig convertToEntity(ImportFieldConfig dto) {
        DiyImportFieldConfig entity = new DiyImportFieldConfig();
        BeanUtil.copyProperties(dto, entity);
        entity.setSortOrder(dto.getSort()); // 字段名映射
        return entity;
    }
}
